package com.hxs.learn.service.core;

import java.io.Serializable;

import java.util.Date;
import java.util.List;

import org.mindrot.jbcrypt.BCrypt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;

import com.hxs.learn.common.page.Page;
import com.hxs.learn.common.page.PageHelper;
import com.hxs.learn.common.page.PageWrapper;
import com.hxs.learn.common.result.Result;
import com.hxs.learn.common.web.LoginInfo;
import com.hxs.learn.constants.core.sql.SqlColConts;
import com.hxs.learn.entity.core.SysUser;
import com.hxs.learn.mapper.core.SysUserMapper;
import com.hxs.learn.shiro.credential.BCryptPasswordService;

/**
 * @author huxinsheng
 * @data 2018-04-24
 */
@Service
public class SysUserService {
    private Logger logger = LoggerFactory.getLogger(SysUserService.class);
    private final SysUserMapper userMapper;

    @Autowired
    public SysUserService(SysUserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 查询所有
     *
     * @return List<SysUser>
     */
    public List<SysUser> findAllSysUser() {
        return userMapper.selectList(new EntityWrapper<>(new SysUser()));
    }

    /**
     * 按主键查询
     *
     * @param id 主键id
     * @return SysUser
     */
    public SysUser findById(Serializable id) {
        return userMapper.selectById(id);
    }

    public SysUser findByLoginName(String username) {
        SysUser user = new SysUser();

        user.setLoginName(username);

        return userMapper.selectOne(user);
    }

    /**
     * 分页查询
     *
     * @param page    分页对象
     * @param keyword 分页条件对象
     * @return PageWrapper<SysUser>
     */
    public PageWrapper<SysUser> findSysUserPageData(Page page, String keyword) {
        EntityWrapper<SysUser> wrapper = new EntityWrapper<>();

        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like(SqlColConts.REAL_NAME, keyword, SqlLike.RIGHT)
                    .or()
                    .like(SqlColConts.LOGIN_NAME, keyword, SqlLike.RIGHT);
        }

        if (!StringUtils.isEmpty(page.getField())) {
            wrapper.orderBy(page.getField(), page.isSort());
        }

        PageWrapper<SysUser> pageWrapper = PageHelper.getPageData(userMapper, page, wrapper);
        List<SysUser> sysUsers = pageWrapper.getRows();

        return pageWrapper;
    }

    /**
     * 修改密码
     *
     * @param loginInfo 登录用户信息
     * @param sysUser   需要修改的用户信息
     * @return 操作结果
     */
    public Result modifyPwd(LoginInfo loginInfo, SysUser sysUser) {
        if (StringUtils.isEmpty(sysUser.getPassword())) {
            return Result.error("旧密码不能为空!");
        }

        SysUser user = userMapper.selectById(loginInfo.getUserId());
        boolean checkStates = BCrypt.checkpw(sysUser.getPassword(), user.getPassword());

        if (!checkStates) {
            return Result.error("旧密码输入不正确!");
        }

        BCryptPasswordService passwordService = new BCryptPasswordService();
        String password = passwordService.encryptPassword(sysUser.getNewPwd());

        user.setPassword(password);
        user.setUpdateBy(loginInfo.getLoginName());
        user.setUpdateTime(new Date());
        userMapper.updateById(user);

        return Result.ok();
    }

    /**
     * 修改用户状态
     *
     * @param loginInfo 登录用户信息
     * @param id        用户id
     * @param status    用户状态
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result modifyUserStatus(LoginInfo loginInfo, String id, Integer status) {
        SysUser userPojo = new SysUser();

        userPojo.setUpdateBy(loginInfo.getLoginName());
        userPojo.setUpdateTime(new Date());
        userPojo.setId(id);
        userPojo.setStatus(status);
        userMapper.updateById(userPojo);

        return Result.ok();
    }

    /**
     * 按主键删除
     *
     * @param loginInfo 登录用户信息
     * @param id        主键id
     */
    @Transactional(rollbackFor = Exception.class)
    public Result removeById(LoginInfo loginInfo, Serializable id) {
        userMapper.deleteById(id);

        return Result.ok();
    }

    /**
     * 重置密码
     *
     * @param sysUser 需要重置的用户信息
     * @return 重置结果
     */
    public Result resetPwd(SysUser sysUser) {
        SysUser condition = new SysUser();

        condition.setLoginName(sysUser.getLoginName());

        SysUser user = userMapper.selectOne(condition);

        if (null == user) {
            return Result.error(Result.USER_NOT_FOUND);
        }

        BCryptPasswordService passwordService = new BCryptPasswordService();
        String password = passwordService.encryptPassword(sysUser.getPassword());

        sysUser.setId(user.getId());
        sysUser.setPassword(password);
        userMapper.updateById(sysUser);

        return Result.ok();
    }

    /**
     * 保存
     *
     * @param sysUser
     */
    @Transactional(rollbackFor = Exception.class)
    public Result save(LoginInfo loginInfo, SysUser sysUser) {
        sysUser.setUpdateBy(sysUser.getLoginName());
        sysUser.setUpdateTime(new Date());

        Wrapper<SysUser> wrapper = new EntityWrapper<>();

        if (StringUtils.isEmpty(sysUser.getId())) {
            wrapper.eq(SqlColConts.LOGIN_NAME, sysUser.getLoginName());
        } else {
            wrapper.eq(SqlColConts.LOGIN_NAME, sysUser.getLoginName()).and().ne(SqlColConts.ID, sysUser.getId());
        }

        int count = userMapper.selectCount(wrapper);

        if (count > 0) {
            return Result.error("登录用户名已存在!");
        }

        if (StringUtils.isEmpty(sysUser.getId())) {
            sysUser.setId(SysUser.newId());
            sysUser.setCreator(loginInfo.getLoginName());
            sysUser.setCreateTime(new Date());
            sysUser.setStatus(0);

            BCryptPasswordService passwordService = new BCryptPasswordService();
            String password = passwordService.encryptPassword(sysUser.getPassword());

            sysUser.setPassword(password);
            userMapper.insertAllColumn(sysUser);
        } else {
            userMapper.updateById(sysUser);
        }

        return Result.ok();
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
